import api from "@/plugins/api"
import md5 from 'js-md5';
export default {
	state: {
		hasLogin: false,
		loginProvider: "",
		openid: null,
		isModelShow: false,
		userInfo: null,
		wxInfo: null,
		userId: null,
		token: null,
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
			state.isModelShow = false
			state.userInfo = null
			state.state.wxInfo = null
			state.userId = null
			state.token = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		setWxInfo(state, wxInfo) {
			state.wxInfo = wxInfo
		},
		setIsAuto(state, isAuto) {
			state.isAuto = isAuto
		},
		setUserId(state, userId) {
			state.userId = userId
		},
		setToken(state, token) {
			state.token = token
		},
		setIsModelShow(state, isModelShow) {
			state.isModelShow = isModelShow
		},
	},
	actions: {
		setInfo: function({
			commit
		}, data) {
			commit('setOpenid', data.wxInfo.openid)
			commit('setWxInfo', data.wxInfo)
			commit('setUserInfo', data.userInfo)
			commit('setUserId', data.userInfo.user_id)
			commit('setIsModelShow', data.isModelShow)
		},
		initWxUserData: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve();
				} else {
					uni.login({
						provider: 'weixin',
						success: (data) => {
							commit('login', 'wx')
							api["data/wxLogin"]({
								code: data.code
							}).then(({
								code,
								data,
								msg
							}) => {
								if (code == 0) {
									commit('setOpenid', data.wxInfo.openid)
									commit('setWxInfo', data.wxInfo)
									commit('setUserInfo', data.userInfo)
									commit('setUserId', data.userInfo.user_id)
									commit('setToken', data.token)
									commit('setIsModelShow', data.isModelShow)
									resolve()
								} else {
									console.log('服务器请求错误', msg)
									reject(msg)
								}
							});
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
						}
					})
				}
			});
		},
		initWebUserData: async function({
			commit,
			state
		}, loginInfo) {
			return await new Promise((resolve, reject) => {
				if (state.userId) {
					resolve();
				} else {
					commit('login', 'web')
					api["data/webLogin"]({
						username:loginInfo.username,
						password:md5("Yttrium-App-" + loginInfo.password)
					}).then(({
						code,
						data,
						msg
					}) => {
						if (code == 0) {
							commit('setUserInfo', data)
							commit('setUserId', data.user_id)
							commit('setToken', data.token)
							commit('setIsModelShow', false)
							resolve()
						} else {
							console.log('服务器请求错误', msg)
							reject(msg)
						}
					});
				}
			});
		}
	}
}
